package org.springframework.validation.mvc;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindException;
import org.springframework.validation.mvc.annotations.ValidationFailureView;
import org.springframework.validation.util.RequestUtils;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

public class AnnotatedErrorViewValidationFailureRedirector implements HandlerExceptionResolver {

	@Autowired
	private ControllerMethodNegotiator controllerMethodNegotiator;
	
	public ModelAndView resolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {
		ModelAndView mav = null;
		if (ex instanceof BindException) {
			//handlerAdapter.
			ValidationFailureView failView = (ValidationFailureView) controllerMethodNegotiator
				.getAnnotationFromControllerMethod(handler, request, ValidationFailureView.class);
			if (failView == null) {
				return null;
			}
			String[] candidateViewNames = failView.value();
			String[] controllerPaths = RequestUtils.getControllerRequestPaths(handler);
			String viewName = RequestUtils.findMatchingRestPath(candidateViewNames, controllerPaths, request);
			if (viewName == null) {
				return null;
			}
			viewName = RequestUtils.replaceRestPathVariables(viewName, ((BindException)ex).getModel(), request);
			mav = new ModelAndView(viewName, ((BindException)ex).getModel());
		}
		return mav;
	}
	
}
